/*
 * Copyright 2010 Yaroslav Klymko aka t3hnar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.t3hnar.io.serializer.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.InputStream;

/**
 * @author Yaroslav Klymko aka t3hnar
 */
public class InputStreamHandler extends FieldHandler<InputStream> {
// ------------------------------ FIELDS ------------------------------

    private static final Class<InputStream> INPUT_STREAM_CLASS = InputStream.class;
    public static final String INPUT_STREAM = "inputStream";

    private static final Log LOG = LogFactory.getLog(InputStreamHandler.class);

// --------------------------- CONSTRUCTORS ---------------------------

    protected InputStreamHandler() {
        super(INPUT_STREAM, INPUT_STREAM_CLASS);

        LOG.debug("Initializing InputStreamHandler");
    }

// -------------------------- OTHER METHODS --------------------------

    @Override
    public InputStream toInstance(final InputStream inputStream) throws ToInstanceException {
        LOG.debug("Retrieving instance; inputStream: " + inputStream);
        if (inputStream == null) {
            throw new IllegalArgumentException("InputStream is null");
        }

        return inputStream;
    }

    @Override
    public InputStream toStream(final Object instance) throws ToStreamException {
        LOG.debug("Retrieving stream; instance: " + instance);
        if (instance == null) {
            throw new IllegalArgumentException("Instance is null");
        }

        if (instance instanceof InputStream) {
            return (InputStream) instance;
        } else {
            final String message = "Instance is not an instance of InputStream";
            LOG.debug(message);
            throw new IllegalArgumentException(message);
        }
    }
}
